package cn.zhaoyuening.rpcdemo.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;

public class RpcConsumer {
	private String host;
	private int port;
	
	public RpcConsumer(String host,int port){
		this.host = host;
		this.port = port;
	}
	
	/**
	 * 获取动态代理对象
	 * @param interfaceClass
	 * @return
	 */
	public <T> T getRemoteObj(Class<T> interfaceClass){
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(interfaceClass);
		enhancer.setCallback(new InvocationHandler() {
			private Socket socket;
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				socket = new Socket(host, port);

				ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
				ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
				
				String className = interfaceClass.getName();
				oos.writeUTF(className);
				oos.writeUTF(method.getName());
				oos.writeObject(method.getParameterTypes());
				oos.writeObject(args);
				
				Object result = ois.readObject();
				return result;
			}
		});
		
		
		return (T) enhancer.create();
	}
}
